//
//  SendTableViewCell.m
//  leo
//
//  Created by 常艳 on 15/10/4.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "SendTableViewCell.h"
#import "LeoMsg.h"
#import "ReceiveTableViewCell.h"
#import "AppDelegate.h"
@implementation SendTableViewCell

- (void)awakeFromNib {
    // Initialization code
    [self.headImg.layer setMasksToBounds:YES];
    self.headImg.layer.cornerRadius=self.headImg.bounds.size.width/2;
    self.headImg.clipsToBounds=YES;
    self.is_play=NO;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(startPlay:)];
    tap.delegate=self;
    self.voiceImg.userInteractionEnabled=YES;
    [self.voiceImg addGestureRecognizer:tap];
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
    if(self.syncManager==NULL||self.dataManager==NULL)
    {
        [LeoMsg showToastMsg:@"程序发生错误，code is 42" parentView:self showPosition:TOAST_SHOW_MID hideAfterDelay:1];
        return;
    }
    
}
-(void)initUI
{
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL&&mydelegate.sendCell!=NULL)
    {
        if(mydelegate.sendCell==self)
        {
            self.voiceBtn.imageView.animationImages=[NSArray arrayWithObjects:
                                                     [UIImage imageNamed:@"voice_b_anim1@2x.png"],
                                                     [UIImage imageNamed:@"voice_b_anim2@2x.png"],
                                                     [UIImage imageNamed:@"voice_b_anim3@2x.png"],                                           nil];
            [self.voiceBtn.imageView setAnimationDuration:2.0f];
            [self.voiceBtn.imageView startAnimating];
        }
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (IBAction)startPlay:(UITapGestureRecognizer *)sender
{
    [self playAction];
}
- (IBAction)playRecord:(id)sender
{
    [self playAction];
}
-(void)playAction
{
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate.sendCell!=NULL)
    {
        if(mydelegate.sendCell!=self)
        {
            [mydelegate.sendCell stop];
            mydelegate.sendCell=NULL;
        }
    }
    if(mydelegate.receiveCell!=NULL)
    {
        [mydelegate.receiveCell stop];
        mydelegate.receiveCell=NULL;
    }
    mydelegate.sendCell=self;
    if(!self.is_play)
    {
        self.voiceBtn.imageView.animationImages=[NSArray arrayWithObjects:
                                                 [UIImage imageNamed:@"voice_b_anim1@2x.png"],
                                                 [UIImage imageNamed:@"voice_b_anim2@2x.png"],
                                                 [UIImage imageNamed:@"voice_b_anim3@2x.png"],                                           nil];
        [self.voiceBtn.imageView setAnimationDuration:2.0f];
        [self.voiceBtn.imageView startAnimating];
        [self play:self.recordPath];
        self.is_play=YES;
    }
    else
    {
        [self.player stop];
        [self.voiceBtn.imageView stopAnimating];
        self.voiceBtn.imageView.animationImages=NULL;
        self.is_play=NO;
    }

}
-(void)play:(NSString *)path
{
    if(path==NULL)
    {
        NSLog(@"%@,play,path is null.",send_tag);
        return;
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    path=[documentsDirectory stringByAppendingString:path];
    NSLog(@"%@,play,path is %@.",send_tag,path);
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:path];
    if(find)
    {

        AVAudioSession *audioSession=[AVAudioSession sharedInstance];
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
        NSError *error=nil;
        self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:path] error:&error];
        if(error!=nil)
        {
            NSLog(@"%@,playRecord,create player error,error is %@.",send_tag,error);
            return;
        }
        self.player.delegate=self;
        self.player.numberOfLoops=0;
        [self.player setVolume:1.0];
        [self.player prepareToPlay];
        [self.player play];
    }
    else
    {
        NSLog(@"%@,playRecord,the record file is not exist.",send_tag);
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self stop];
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL&&mydelegate.sendCell!=NULL)
    {
        if(mydelegate.sendCell==self)
            mydelegate.sendCell=NULL;
    }
}
-(void)stop
{
    if(self.player!=NULL)
    {
        [self.player stop];
        [self.voiceBtn.imageView stopAnimating];
        self.voiceBtn.imageView.animationImages=NULL;
    }
    self.is_play=NO;
}
-(void)initData
{
     AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(self.chat==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 43"];
        return;
    }
    if(self.chat.is_send==1)//is_send=1发送成功
    {
        self.failBtn.enabled=NO;
        self.failBtn.hidden=YES;
        self.durationLable.hidden=NO;
        self.voiceBtn.hidden=NO;
        self.voiceBtn.enabled=YES;
        if(self.chat.duration>0)
        {
            self.durationLable.text=[NSString stringWithFormat:@"%d''",self.chat.duration];
        }
        else
        {
            self.durationLable.text=@"0''";
        }
        self.recordPath=self.chat.file_url;

    }
    else
    {
        self.voiceBtn.enabled=NO;
        self.voiceBtn.hidden=YES;
        self.indicator.hidden=NO;
        self.durationLable.hidden=YES;
        [self.indicator startAnimating];
        if(self.type==1&&mydelegate!=NULL&&mydelegate.isResending==NO)
        {
            BOOL isSend=[self.dataManager isChatSend:self.chat.chatId];
            if(isSend==1)
            {
                [self hasSendSuccess];
            }
            else
            {
                [self.syncManager uploadGroupChatRecord:self.chat completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    [self callback:result retValue:retValue description:description];
                }];
            }

        }
        else if((self.type==2||self.type==3)&&mydelegate!=NULL&&mydelegate.isResending==NO)
        {
            BOOL isSend=[self.dataManager isChatSend:self.chat.chatId];
            if(isSend==1)
            {
                [self hasSendSuccess];
            }
            else
            {
                [self.syncManager uploadSingleChatRecord:self.chat completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    [self callback:result retValue:retValue description:description];
                }];
            }

        }

    }
    if(self.chat.showTime&&self.chat.genTime!=NULL&&![self.chat.genTime isEqualToString:@"(null)"])
    {
        self.timeLable.text=[Tooler getDateTime:self.chat.genTime];
    }
    else
    {
        self.timeLable.text=@"";
    }

}

-(void)callback:(SyncResult) result retValue:(NSDictionary *)ret description:(NSString *)description
{

    if(result==SUCESS)
    {
        self.failBtn.enabled=NO;
        self.failBtn.hidden=YES;
        self.indicator.hidden=YES;
        [self.indicator stopAnimating];
        self.voiceBtn.enabled=YES;
        self.voiceBtn.hidden=NO;
        self.durationLable.hidden=NO;
        if(self.chat.duration>0)
        {
            self.durationLable.text=[NSString stringWithFormat:@"%d''",self.chat.duration];
        }
        else
        {
            self.durationLable.text=@"0''";
        }
        self.recordPath=self.chat.file_url;
        //删除amr文件
        [self deleteAmrFile];

    }
    else
    {
        NSLog(@"sync fail,error is %@",description);
        self.indicator.hidden=YES;
        [self.indicator stopAnimating];
        self.failBtn.enabled=YES;
        self.failBtn.hidden=NO;
    }
}
-(void)deleteAmrFile
{
    NSString *file_url=[[Tooler getDocumentDirectory] stringByAppendingString:self.chat.amr_url];
    if(file_url==NULL)
    {
        NSLog(@"%@,deleteAmrFile,file_url is null.",send_tag);
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err=nil;
    [fileManager removeItemAtPath:file_url error:&err];
    if(err!=nil)
    {
        NSLog(@"%@,deleteAmrFile,delete file error,error is %@.",send_tag,err);
    }
}
-(void)hasSendSuccess
{
    self.failBtn.enabled=NO;
    self.failBtn.hidden=YES;
    self.indicator.hidden=YES;
    [self.indicator stopAnimating];
    self.voiceBtn.enabled=YES;
    self.voiceBtn.hidden=NO;
    self.durationLable.hidden=NO;
    if(self.chat.duration>0)
    {
        self.durationLable.text=[NSString stringWithFormat:@"%d''",self.chat.duration];
    }
    else
    {
        self.durationLable.text=@"0''";
    }
    self.recordPath=self.chat.file_url;
}
- (IBAction)resend:(id)sender {
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL&&mydelegate.isResending==YES)
        return;
    BOOL isSend=[self.dataManager isChatSend:self.chat.chatId];
    if(isSend==1)
    {
        [self hasSendSuccess];
        return;
    }
    [self initData];
}

@end
